<template>
  <Viewer :router="viewerRouter" @back="popularKey = null"></Viewer>
</template>

<script setup>
import { defineAsyncComponent, watch } from 'vue'
import { storeToRefs } from 'pinia'
import { useDesktopViewerStore } from '@/store/desktop-viewer'
import { useNavRefresh } from '@/compositions/nav/refresh'
import { useInfinite } from '@/compositions/request/infinite'
import { useDesktopViewerRouter } from '@/compositions/viewer/router/desktopViewerRouter'
import { MEDIA_TYPE, NAVS } from '@/constant'
import { MEDIA_TOGGLE_TYPE } from '@/constant/viewer-router'
import API from '@/http'

const Viewer = defineAsyncComponent(() => import('@/components/viewer/Viewer.vue'))

const desktopViewerStore = useDesktopViewerStore()
const { popularKey } = storeToRefs(desktopViewerStore)
const { popularSetInit, refreshPopular } = desktopViewerStore

const viewerRouter = useDesktopViewerRouter('desktop-home-popular')
const { setFromMainViewer } = viewerRouter

let prevHotDate
watch(popularKey, (v) => {
  if (v) {
    if (prevHotDate === v) {
      return
    }

    prevHotDate = v

    const fetcher = {
      video: useInfinite({
        request: API.Media.getPopularSet,
        params: { type: MEDIA_TYPE.VIDEO, hot_date: v },
      }),
      photo: useInfinite({
        request: API.Media.getPopularSet,
        params: { type: MEDIA_TYPE.PHOTO, hot_date: v },
      }),
    }

    setFromMainViewer(fetcher, MEDIA_TOGGLE_TYPE.SWITCHER)
  }
})

popularSetInit()

// nav 點擊原本頁面刷新
useNavRefresh(NAVS.HOME, refreshPopular)
</script>
